package designPattern.Observer_delegate;

import java.lang.reflect.Method;

/**
 * <pre>类名: Event</pre>
 * <pre>描述: 通过反射，实现对事件的封装</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/3/19 14:19</pre>
 * <pre>作者: chenwb</pre>
 */
public class Event {

	private Object target;

	private String methodName;

	private Object[] params;

	private Class[] paramsTypes;

	public Event(Object target, String methodName, Object[] params) {
		this.target = target;
		this.methodName = methodName;
		this.params = params;
		createParamsTypes(params);
	}
	/**
	 * @Description: 获取参数类型，反射时用
	 * @author chenwb
	 * @date 2020/3/19 14:55
	 * @param params
	 */
	private void createParamsTypes(Object[] params) {
		paramsTypes = new Class[params.length];
		for (int i = 0; i < params.length; i++) {
			paramsTypes[i] = params[i].getClass();
		}
	}

	/**
	 * @Description: invoke方法，就是Observer的update方法
	 * @author chenwb
	 * @date 2020/3/19 14:55
	 */
	public void invoke() {
		Method method = null;
		try {
			method = target.getClass().getMethod(methodName, paramsTypes);
			method.invoke(target, params);
		} catch (Exception e) {
			System.out.println("委托执行异常，异常原因：" + e.getMessage());
			// no to do
		}
	}
}
